package com.schoolComments.common;

import cn.hutool.core.bean.BeanUtil;
import com.schoolComments.dto.UserDTO;
import com.schoolComments.utils.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author 马园博
 * @date 2023/04/06/16:58
 * @Project hm-dianping
 **/
public class RefreshTockenInterceptor implements HandlerInterceptor {
    //这个对象是我们在构造时自己传入的(MvcConfig) 因为这个类并没有加入到bean的管理中 所以不能用注解注入
    private StringRedisTemplate stringRedisTemplate;
    public RefreshTockenInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取前端带过来的token
        String token = request.getHeader("authorization");
        if (token == null) {
            //前端没有带过来token 那就说明压根没登录过
            return true;
        }
        //去redis中找对应用户的信息
        Map<Object, Object> userMap = stringRedisTemplate.opsForHash().entries("userLogin:token:" + token);
        if (userMap.isEmpty()) {
            //当前登录过期(既redis中已经删除了相应的token和它的value)
            return true;
        }
        //将hashmap转为UserDto对象 并存入ThreadLocal中供本次线程使用
        UserDTO userDTO = BeanUtil.fillBeanWithMap(userMap, new UserDTO(), false);
        UserHolder.saveUser(userDTO);
        //刷新token的过期时间
        stringRedisTemplate.expire("userLogin:token:" + token, 30, TimeUnit.MINUTES);
        return true;
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}